import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document, ObjectId } from 'mongoose';
import { EveryDayIsDocument, EveryDayIsSchema } from './every-day-is.schema';
import * as dayjs from 'dayjs';
import * as utc from 'dayjs/plugin/utc';
import 'dayjs/locale/zh-cn';
import * as isSameOrAfter from 'dayjs/plugin/isSameOrAfter';

dayjs.locale('zh-cn');
dayjs.extend(utc);
dayjs.extend(isSameOrAfter);

export type GameDocument = Game & Document;

/**
 * 取得这一场游戏的第一天开盘
 */
const getFirstDayOpenTime = (): number => {
  const now = dayjs.utc();
  const todayOpenTime = now.startOf('d').add(1, 'h').add(30, 'm');
  const hasOpened = now.isSameOrAfter(todayOpenTime);
  const tomorrowOpenTime = now
    .startOf('d')
    .add(1, 'd')
    .add(1, 'h')
    .add(30, 'm');

  // 判断当天有没有过了开盘时间。如果有，则开始时间是第二天的开盘时间；如果没有，则今天的开盘时间，就是开始时间
  if (hasOpened) {
    return tomorrowOpenTime.valueOf();
  }
  return todayOpenTime.valueOf();
};

@Schema()
export class Game {
  /**
   * 天数
   */
  @Prop()
  days: number;

  /**
   * 每天所需要的积分
   */
  @Prop()
  everyDayIntegral: number;

  /**
   * 参与的用户
   */
  @Prop()
  users: ObjectId[];

  /**
   * 每天情况
   */
  @Prop({ type: Map, of: EveryDayIsSchema })
  everyDayIs: Map<string, EveryDayIsDocument>;

  /**
   * 创建时间
   */
  @Prop({ type: Date, default: Date.now })
  creationTime: Date;

  /**
   * 游戏是否结束
   */
  @Prop({ type: Boolean, default: false })
  isOver: boolean;

  /**
   * 这一场游戏的第一天开始时间
   */
  @Prop({ type: Date, default: getFirstDayOpenTime })
  firstDayOpenTime: Date;
}

export const GameSchema = SchemaFactory.createForClass(Game);
